package main;

import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;

public class Field {
	private Snake snake;
	private Food food;
	private int[] SIZE;
	private int[][] lattices;

	private void flushLattices() {
		for (int[] i : lattices) {
			for (int j = 0; j < i.length; j++) {
				i[j] = 0;
			}
		}
	}

	public Field(int row, int col) {
		System.out.println(row);
		System.out.println(col);
		this.snake = new Snake(new int[] { row / 2, col / 2 });
		this.food = new Food(row, col);
		this.SIZE = new int[] { row, col };
		this.lattices = new int[SIZE[0]][SIZE[1]];
	}

	public int getState(int row, int col) {
		return lattices[row][col];
	}

	public int[][] step() {
		snake.crawl();
		this.flushLattices();
		List<int[]> nodes = snake.getNodes();
		// 撞墙判定
		if (nodes.get(0)[0] < 0 || nodes.get(0)[0] >= SIZE[0] || nodes.get(0)[1] < 0
				|| nodes.get(0)[1] >= SIZE[1]) {
			snake.setStatus(false);
			snake = new Snake(new int[] { SIZE[0] / 2, SIZE[1] / 2 });
			nodes = snake.getNodes();
		}
		// 食物
		this.lattices[food.getCoord()[1]][food.getCoord()[0]] = 2;
		// 蛇身
		for (int[] n : nodes) {
			this.lattices[n[1]][n[0]] = 1;
		}
		// 吃东西判定
		if (Arrays.equals(food.getCoord(), nodes.get(0))) {
			StringBuilder str = new StringBuilder("吃到了位于");
			str.append(Arrays.toString(food.getCoord()));
			str.append("的食物，当前长度：");
			str.append(nodes.size());
			System.out.println(str.toString());
			snake.grow();
			this.food.flush();
		}
		return this.lattices;
	}

	public void keyboard(KeyEvent e) {
		int code = e.getKeyCode();
		// 仅限上下左右键
		if (code < 41 && code > 36) {
			snake.changeDir(code);
		}
		// System.out.println(e.getKeyCode());
	}

	@Override
	public String toString() {
		StringBuffer str = new StringBuffer();
		for (int row = 0; row < lattices.length; row++) {
			for (int col = 0; col < lattices[row].length; col++) {
				str.append(lattices[row][col]);
			}
			str.append("\n");
		}
		return str.toString();
	}

	public int getScore() {
		return snake.length() - 1;
	}
}